package com.dongdongshop.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.dongdongshop.constant.HttpResultEnum;
import com.dongdongshop.data.DataResult;
import com.dongdongshop.pojo.data.PageBean;
import com.dongdongshop.pojo.item.TbItem;
import com.dongdongshop.util.HttpClientUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @Author Eayon
 * @Date 2020/4/3 18:31
 */
@Controller
@RequestMapping("search")
public class SearchController {

    private static final Logger log = LoggerFactory.getLogger(SearchController.class);

    private static final String SEARCH_URL = "http://localhost:8765/searchservice/search/";

    /**
     * 跳转搜索列表页
     * @param keyword
     */
    @RequestMapping("toSearch")
    public String toSearch(String keyword, Model model){
        model.addAttribute("keyword",keyword);
        return "search";
    }

    /**
     * 根据关键字去ES中查询商品信息
     * @param keyword
     */
    @RequestMapping("searchItemByKeyword")
    @ResponseBody
    public DataResult searchItemByKeyword(String keyword, @RequestParam(defaultValue = "1")Integer pageNum,
                                          @RequestParam(defaultValue = "10")Integer pageSize){
        PageBean<TbItem> page = null;
        try {
            //调用搜索服务查询
            //设置请求参数
            Map<String,String> params = new HashMap<>();
            params.put("pageNum",pageNum.toString());
            params.put("pageSize",pageSize.toString());
            //该服务接收的是路径参数，但是还是要给一个空的MAP
            String dataResultStr = HttpClientUtil.doGet(SEARCH_URL + keyword, params);
            DataResult dataResult = JSON.parseObject(dataResultStr, DataResult.class);
            Object pageObj = dataResult.getData();
            String pageStr = JSONObject.toJSONString(pageObj);
            page = JSONObject.parseObject(pageStr, PageBean.class);
            System.out.println(page);
        }catch (Exception e){
            log.error("搜索商品异常",e);
            return new DataResult(HttpResultEnum.ERROR.getCode(),HttpResultEnum.ERROR.getMessage());
        }
        return new DataResult(HttpResultEnum.SUCCESS.getCode(),HttpResultEnum.SUCCESS.getMessage(),page);
    }
}
